'use strict';

const Service = require('egg').Service;

class WeappService extends Service {
  // 微信登录
  async login(code) {
    const { app } = this;
    const session = await this.jscode2session(code, app.config.weapp.appid, app.config.weapp.secret);
    // 更新用户信息
    let user = await app.getModel('weappUser').findOneAndUpdate({ openid: session.openid }, { session: session.session, lastLoginAt: Date.now() });
    if (!user) user = await app.getModel('weappUser').create({ openid: session.openid, unionid: session.unionid, session: session.session, lastLoginAt: Date.now() });
    return user._doc;
  }
  // 项目中心登录
  async plogin(code) {
    const { app, ctx } = this;
    const { token, gid } = await ctx.service.pcenter.centerPost('/project/login/miniProgram', { code, appid: app.config.weapp.appid });
    let user = await app.getModel('pcenterUser').findOne({ gid });
    if (!user) user = await app.getModel('pcenterUser').create({ gid });
    return { token, user: user._doc };
  }
  async auth(user, encryptedData, iv) {
    const { app } = this;
    const info = await this.ctx.helper.decodeEncryptedData(app.config.weapp.appid, user.session, encryptedData, iv);
    const weappUser = await app.getModel('weappUser').findByIdAndUpdate(user._id, { avatarUrl: info.avatarUrl, nickName: info.nickName });
    return weappUser;
  }
  // 获取微信accessToken
  async getAccessToken(appid, appSecret) {
    const { ctx, app } = this;
    const cacheKey = `at:${appid}`;
    const cache = await app.redis.get(cacheKey);
    if (cache) return cache;
    const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appSecret}`;
    const { res } = await ctx.curl(url, { dataType: 'json' });
    app.redis.set(cacheKey, res.data.access_token);
    app.redis.expire(cacheKey, res.data.expires_in - 200);
  }
  async jscode2session(code, appid, appSecret) {
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`;
    const { res: { data } } = await this.ctx.curl(url, { dataType: 'json' });
    if (data.errcode) this.ctx.throwBizError(data.errmsg);

    return {
      openid: data.openid,
      session: data.session_key,
      unionid: data.unionid,
    };
  }
}

module.exports = WeappService;
